package mrms.api.web.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author lenchu
 * @date 2019/02/02
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    private final List<Authentication> authentications;

    public AuthenticationInterceptor(List<Authentication> authentications) {
        this.authentications = authentications;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String s = "";
        while ((s = reader.readLine()) != null) {
            sb.append(s);
        }
        String body = sb.toString();
        ObjectMapper mapper = new ObjectMapper();
        Map map = new HashMap(0);
        try {
            map = mapper.readValue(body, Map.class);
        } catch (Exception e) {
            log.info("login without request body");
        }
        List<String> errors = new LinkedList<>();
        map.put("errors", errors);
        for (Authentication a : authentications) {
            a.authenticate(request, response, map);
        }
        if (errors.size() > 0) {
            throw new AuthenticationException(errors);
        }
        return true;
    }
}
